package com.jweb.framework.service.sqlmap.support;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;


import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.logging.jdbc.ConnectionLogger;
import org.apache.ibatis.transaction.Transaction;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.util.Assert;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：事务的处理
 */
public class SpringManagedTransaction implements Transaction {
	
	private final Log log = LogFactory.getLog(super.getClass());
	private final Connection connectionProxy ;
	private final Connection connection ;
	private final DataSource dataSource ;
	private final boolean flag ;
	
	public SpringManagedTransaction(Connection connection , DataSource dataSource){
		Assert.notNull(connection , "No Connection specified");
		Assert.notNull(dataSource , "No DataSource specified");
		
		this.connectionProxy = connection ;
		this.dataSource = dataSource ;
		this.connection = getConnection(connection);
		this.flag = DataSourceUtils.isConnectionTransactional(this.connection , dataSource);
	}
	
	
	private Connection getConnection(Connection connection){
		if(Proxy.isProxyClass(connection.getClass())){
			InvocationHandler invocationHandler = Proxy.getInvocationHandler(connection);
			if(invocationHandler instanceof ConnectionLogger){
				return ((ConnectionLogger) invocationHandler).getConnection();
			}
		}
		
		return connection ;
	}
	
	public void close() throws SQLException{
		DataSourceUtils.releaseConnection(this.connection , dataSource);
	}
	
	public void commit() throws SQLException {
		if(!this.flag){
			if(this.log.isDebugEnabled()){
				this.log.debug("Committing JDBC Connection [" + this.connectionProxy + "]");
			}
			this.connectionProxy.commit() ;
		}
	}
	
	public Connection getConnection(){
		return this.connectionProxy ;
	}
	
	public void rollback() throws SQLException{
		if(!this.flag){
			if(this.log.isDebugEnabled()){
				this.log.debug("Rolling back JDBC Connection [" + this.connectionProxy + "]");
			}
			
			this.connectionProxy.rollback();
		}
	}
	
	
	
}
